package com.zHan.controller;

import com.zHan.pojo.Emp;
import com.zHan.pojo.Result;
import com.zHan.service.EmpService;
import com.zHan.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private EmpService empService;

    /**
     * 用户登录
     *
     * @param emp
     * @return
     */
    @PostMapping
    public Result login(@RequestBody Emp emp) {
        //调用业务层
        Emp loginEmp = empService.login(emp);

        //判断登录用户是否存在
        if (loginEmp != null) {
            //构造jwt的有效载荷
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginEmp.getId());
            claims.put("username", loginEmp.getUsername());
            claims.put("password", loginEmp.getPassword());

            //生成jwt令牌
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        }

        return Result.error("用户名或密码错误，登录失败");
    }
}
